<template class="firstpage">
  <div>
    <div class="boxMargin">
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">视频名称：</el-col>
              <el-col :span="14">
                <el-input v-model="searchData.videoName" placeholder="请输入视频名称" />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">视频ID：</el-col>
              <el-col :span="14">
                <el-input v-model="searchData.videoId" placeholder="请输入视频ID" />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">创建时间：</el-col>
              <el-col :span="14">
                <el-date-picker v-model="customData.createTime" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 100%;" @change="createTimeChange($event)" />
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="margin">
          <el-col :span="24" class="right">
            <el-button type="success" @click="onSearch">查询</el-button>
            <el-button @click="onReset">清空</el-button>
            <el-button type="primary" @click="report">导出报表</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div class="boxMargin">
      <el-card class="box-card">
        <div slot="header">
          <div class="contion-header" style="width:10%;">
            <span>视频列表</span>
          </div>
          <div class="contion-header text-r" style="width:89%;">
            <el-button type="primary" @click="onAdd">视频上传</el-button>
          </div>
        </div>
        <div>
          <el-table :header-cell-style="{'background':'#f8f8f9'}" border :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55"></el-stable-column> -->
            <el-table-column prop="videoId" label="视频ID" />
            <el-table-column prop="videoName" label="视频名称" />
            <el-table-column prop="itemCnt" label="关联商品">
              <template slot-scope="scope">
                <div style="color: #1890ff;cursor: pointer;" @click="commodItem(scope.row)">{{ scope.row.itemCnt ? scope.row.itemCnt : '0' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="videoType" label="格式">
              <template slot-scope="scope">
                <span v-if="scope.row.videoType === 1">flv</span>
                <span v-else-if="scope.row.videoType === 2">mp4</span>
                <span v-else-if="scope.row.videoType === 3">wav</span>
                <span v-else-if="scope.row.videoType === 4">mp3</span>
                <span v-else-if="scope.row.videoType === 5">m4a</span>
                <span v-else-if="scope.row.videoType === 6">mov</span>
                <span v-else />
              </template>
            </el-table-column>
            <el-table-column prop="videoSize" label="大小">
              <template slot-scope="scope">
                <span v-if="scope.row.videoSize != undefined && scope.row.videoSize != null && scope.row.videoSize != ''">{{ scope.row.videoSize }}M</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTtime" label="创建时间" />
            <el-table-column prop="createUser" label="创建人" />
            <el-table-column label="操作" width="350">
              <template slot-scope="scope">
                <el-button type="text" @click="onInfo(scope.row)">查看</el-button>
                <el-button type="text" @click="onUpdate(scope.row)">编辑</el-button>
                <el-button type="text" @click="copyUrl(scope.row)">复制链接</el-button>
                <el-button type="text" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <div class="marginTop20 center">
      <template>
        <PAGER ref="wptxPager" @search="onChangePage" />
      </template>
    </div>
    <el-dialog :title="customData.editTitle" :visible.sync="customData.editVideo" width="40%" center>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" class="demo-ruleForm">
        <el-form-item label="视频名称：" prop="videoName">
          <el-input v-model="form.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="视频简介：">
          <el-input v-model="form.videoDesc" placeholder="请输入视频简介" />
        </el-form-item>
        <el-form-item label="视频上传：" prop="videoUrl">
          <div style="display:flex;">
            <!-- 编辑走的 外网 -->
            <div v-if="customData.status == '2'" class="drawing_div" style="width:212px;height:136px;margin-right:20px;">
              <video :src="form.extDomain + form.videoPreview + form.uploadId" class="avatar" autoplay controls="controls" style="max-width:100%;height:100%">您的浏览器不支持视频播放</video>
            </div>
            <!-- 编辑 uploadId 为空，回显使用腾讯云地址 -->
            <div v-if="customData.status == '22'" class="drawing_div" style="width:212px;height:136px;margin-right:20px;">
              <video :src="form.videoUrl" class="avatar" autoplay controls="controls" style="max-width:100%;height:100%">您的浏览器不支持视频播放</video>
            </div>
            <!-- 创建走的 内网 -->
            <div v-if="customData.status == '3' && form.viewVideoUrl != undefined && form.viewVideoUrl != null && form.viewVideoUrl !== ''" class="drawing_div" style="width:212px;height:136px;margin-right:20px;">
              <video :src="form.videoUrl" class="avatar" autoplay controls="controls" style="max-width:100%;height:100%">您的浏览器不支持视频播放</video>
            </div>
            <el-upload v-if="customData.status == '3'" ref="upload" action :show-file-list="false" :auto-upload="false" :on-change="beforeAvatarUploadType" accept=".mp4">
              <div style="border-radius: 6px;background-color: #fbfdff;width:212px;height:136px;box-sizing:border-box;border:1px dashed #c0ccda;display:flex;justify-content: center;align-items: center;">
                <i class="el-icon-plus" />
              </div>
            </el-upload>
          </div>
          <div class="dece">
            <p>上传说明：</p>
            <p>1：视频格式支持.mp4</p>
            <p>2：最大允许上传200MB视频</p>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">确认</el-button>
          <el-button @click="customData.editVideo = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="视频详情" :visible.sync="customData.detailVideo" width="40%" center>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" class="demo-ruleForm">
        <el-form-item label="视频名称：">
          {{ form.videoName }}
        </el-form-item>
        <el-form-item label="视频简介：">
          {{ form.videoDesc }}
        </el-form-item>
        <el-form-item label="视频链接：">
          {{ form.videoUrl }}&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button plain size="mini" @click="copyUrl(form)">复制链接</el-button>
        </el-form-item>
        <el-form-item label="视频上传：">
          <div style="display:flex;">
            <div v-if="customData.status == '11'" class="drawing_div" style="width:212px;height:136px;margin-right:20px;">
              <video :src="form.videoUrl" class="avatar" autoplay controls="controls" style="max-width:100%;height:100%">您的浏览器不支持视频播放</video>
            </div>
            <div v-if="customData.status == '1'" class="drawing_div" style="width:212px;height:136px;margin-right:20px;">
              <video :src="form.extDomain + form.videoPreview + form.uploadId" class="avatar" autoplay controls="controls" style="max-width:100%;height:100%">您的浏览器不支持视频播放</video>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="视频格式：">
          {{ form.videoType | type }}
        </el-form-item>
        <el-form-item label="视频大小：">
          <span v-if="form.videoSize != undefined && form.videoSize != null && form.videoSize != ''">{{ form.videoSize }}M</span>
        </el-form-item>
        <el-form-item label="创建时间：">
          {{ form.createTime }}
        </el-form-item>
        <el-form-item label="创建人：">
          {{ form.createUser }}
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="关联商品" :visible.sync="customData.commodities" width="60%" center>
      <el-table :data="customData.commoditiesDate" tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="hostItem" label="HostItem" />
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column prop="hostupc" label="Hostupc" />
        <el-table-column prop="categoryName" label="商品分类" />
        <el-table-column prop="brandName" label="品牌" />
      </el-table>
      <div style="margin-top:20px;text-align: center;">
        <el-pagination
          :current-page="pageData.currentPage"
          :page-sizes="pageData.pageSizes"
          :page-size="pageData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import $ from 'jquery'
import _validate from '../../../../framework/commonJs/wptx_validate'
import _tools from '../../../../framework/commonJs/wptx_tools'
import _common from '../../../../framework/commonJs/wptx_common'
import _api from '@/framework/API/material'
import { reportingVideo } from '../../../../framework/API/excel'
import { PAGER } from '@/framework/commonTemplate/'
import { global } from '../../../../filter/global-api'
import { Loading } from 'element-ui'
import SparkMD5 from 'spark-md5'
const _FUNCTION_NAME = ''
export default {
  components: { PAGER },
  filters: {
    type(value) {
      if (value === 1) {
        return 'flv'
      } else if (value === 2) {
        return 'mp4'
      } else if (value === 3) {
        return 'wav'
      } else if (value === 4) {
        return 'mp3'
      } else if (value === 5) {
        return 'm4a'
      } else if (value === 6) {
        return 'mov '
      }
    }
  },
  data() {
    return {
      tableData: [],
      searchData: {
        videoName: '', // 视频名称
        videoId: '', // 视频Id
        fstartCreateTime: '', // (开始)创建时间
        fendCreateTime: '' // (结束)创建时间
      },
      searchDataBuffer: {
        videoName: '', // 视频名称
        videoId: '', // 视频Id
        fstartCreateTime: '', // (开始)创建时间
        fendCreateTime: '' // (结束)创建时间
      },
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },
      dialogData: {},
      historyData: {},
      infoData: {},
      customData: {
        multipleSelection: [],
        createTime: [],
        editTitle: '',
        editVideo: false,
        detailVideo: false,
        status: '',
        commodities: false,
        commoditiesDate: [],
        commodValue: {
          videoId: ''
        }
      },
      tenXunCosData: {
        tenxunCosBucket: '',
        tenxunCosRegion: '',
        tenxunCosSecretKey: '',
        tenxunCosSecretId: ''
      },
      form: {
        videoName: '',
        videoDesc: '',
        videoUrl: '',
        viewVideoUrl: '',
        extDomain: '',
        samsVideoUrl: ''
      },
      rules: {
        videoName: [
          { required: true, message: '请输入视频名称', trigger: 'blur' }
        ],
        videoUrl: [
          { required: true, message: '请上传视频url', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() { },
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
  },
  beforeDestroy() { },
  methods: {
    onInit(data) {
      const self = this
      _api.pageDesc(self, self.$refs.wptxPager.pageData, self.callBack_pageDesc, self.searchData)
    },
    onSearch() {
      const self = this
      const params = self.searchData
      self.searchDataBuffer = _tools.cloneObj(self.searchData)
      self.$refs.wptxPager.resetPageNo()
      _api.pageDesc(self, self.$refs.wptxPager.pageData, self.callBack_pageDesc, params)
    },
    onChangePage(data) {
      const self = this
      const params = self.searchDataBuffer
      _api.pageDesc(self, self.$refs.wptxPager.pageData, self.callBack_pageDesc, params)
    },
    onReset(data) {
      const self = this
      _tools.reset(self.searchData)
      _tools.reset(self.searchDataBuffer)
      self.customData.createTime = []
      self.onInit()
    },
    onAdd() {
      const self = this
      self.customData.editVideo = true
      self.customData.editTitle = '视频上传'
      _tools.reset(self.form)
      self.customData.status = '3'
      self.$nextTick(function() {
        self.$refs['form'].clearValidate()
      })
    },
    onDelete(data) {
      const self = this
      let title = ''
      if (data.itemCnt != 0) {
        title = '该条视频关联了' + data.itemCnt + '个商品，将该条视频删除后，所关联的商品关联关系全部删除，是否删除?'
      } else {
        title = '确认将该条视频删除?'
      }
      self.$confirm(title, '删除视频', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _api.delete(self, data.videoId, self.callBack_delete)
      }).catch(() => {
        _validate.openTip(self, '已取消删除', 'warning')
      })
    },
    onInfo(data) {
      const self = this
      _tools.reset(self.form)
      self.customData.status = '1'
      _api.detail(self, data.videoId, self.callBack_detail)
    },
    onUpdate(data) {
      const self = this
      _tools.reset(self.form)
      self.customData.status = '2'
      _api.detail(self, data.videoId, self.callBack_detail)
    },
    onBathDelete() {
      const self = this
    },
    onBathUpdate() { },
    onDisable(data) {
      const self = this
    },
    onEnable(data) {
      const self = this
    },
    onUpload(data) { },
    onBathUpload() { },
    onExport(data) { },
    onDownload(data) { },
    onHistory(data) { },
    callBack_pageDesc(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.tableData = data.result
        self.$refs.wptxPager.updatePageData(data)
      }
    },
    callBack_pageItem(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.customData.commoditiesDate = data.result
        self.pageData.total = data.totalCount
      }
    },
    // 创建
    callBack_create(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        _validate.openTip(self, '创建成功', 'success')
        self.customData.editVideo = false
        self.onChangePage()
      }
    },
    // 详情
    callBack_detail(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        if (self.customData.status === '1') {
          self.customData.detailVideo = true
          self.$nextTick(function() {
            if (_validate.checkEmpty(data.data.uploadId)) {
              self.customData.status = '11'
            }
            self.form = data.data
          })
        } else if (self.customData.status === '2') {
          self.customData.editVideo = true
          self.customData.editTitle = '视频编辑'
          self.$nextTick(function() {
            if (_validate.checkEmpty(data.data.uploadId)) {
              self.customData.status = '22'
            }
            self.form = data.data
            self.$refs['form'].clearValidate()
          })
        }
      }
    },
    callBack_update(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        _validate.openTip(self, '编辑成功', 'success')
        self.customData.editVideo = false
        self.onChangePage()
      }
    },
    callBack_delete(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        _validate.openTip(self, '删除成功', 'success')
        self.onChangePage()
      }
    },
    handleSelectionChange(val) {
      this.customData.multipleSelection = val
    },
    createTimeChange(value) {
      const self = this
      if (value == '') {
        self.searchData.fstartCreateTime = ''
        self.searchData.fendCreateTime = ''
      } else {
        self.searchData.fstartCreateTime = value[0]
        self.searchData.fendCreateTime = value[1]
      }
    },
    // 模板点击上传 //exhibitionType 商品展示图 videoType 商品视频 detailsType 商品轮播图
    beforeAvatarUploadType(file, fileList) {
      const self = this
      const AllUpExt = '.mp4|'
      const extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isLt10M = file.size / 1024 / 1024 < 200
      if (!isLt10M) {
        _validate.openTip(self, '文件大小不能超过200MB', 'warning')
        return false
      }
      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      self.form.videoSize = (file.size / 1024 / 1024).toFixed(2)
      // 获取腾讯云cos鉴权信息
      self.queryTenXunCosMsg(file)
      // self.itemUpload(file)
    },
    queryTenXunCosMsg(file) {
      const self = this
      self.computeMD5(file)
    },
    // 计算MD5
    computeMD5(file) {
      const self = this
      const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      const fileReader = new FileReader()
      const chunkSize = 2097152
      const chunks = Math.ceil(file.size / chunkSize)
      let currentChunk = 0
      let md5
      // 注意点，网上都是 这一步都是有问题的， SparkMD5.ArrayBuffer()
      const spark = new SparkMD5.ArrayBuffer()
      fileReader.onload = function(e) {
        spark.append(e.target.result)
        currentChunk++
        if (currentChunk < chunks) {
          loadNext()
        } else {
          const sparkEnd = spark.end()
          const dataFile = file.raw
          const params = {
            uploadFile: dataFile,
            fileMd5: sparkEnd
          }
        }
      }
      fileReader.onerror = function() {
      }
      function loadNext() {
        const start = currentChunk * chunkSize
        const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
        // 注意这里的 fileRaw
        fileReader.readAsArrayBuffer(blobSlice.call(file.raw, start, end))
      }
      loadNext()
    },
    // 上传的弹出层选择完视频
    itemUpload(file) {
      const self = this
      const fd = new FormData()
      fd.append('multiFile', file.raw)
      const url = process.env.VUE_APP_VIDEO_UPLOAD
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        if (res.code != 200) {
          _validate.openTip(self, res.message, 'error')
        } else {
          _validate.openTip(self, '视频上传成功', 'success')
          if (res.result) {
            self.form.videoUrl = res.result.videoUrl
            self.form.domainName = res.result.domainName
            self.form.uploadId = res.result.uploadId
            self.form.videoSize = res.result.videoSize
            self.form.fileMd5 = res.result.videoMd5
            self.form.videoType = 2
            self.form.viewVideoUrl = res.result.viewVideoUrl
            self.form.videoPlayTime = res.result.videoDuration
          }
        }
      },
      function(error) {
        self.$message.error(error)
      }
      )
    },
    submitForm(formName) {
      const self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          if (self.customData.editTitle == '视频上传') { // 新建
            _api.create(self, self.form, self.callBack_create)
          } else if (self.customData.editTitle == '视频编辑') {
            _api.update(self, self.form, self.callBack_update)
          }
        } else {
          return false
        }
      })
    },
    // 复制链接
    copyUrl(data) {
      const self = this
      const oInput = document.createElement('input')
      if (_validate.checkEmpty(data.uploadId)) {
        oInput.value = data.samsVideoUrl
      } else {
        oInput.value = data.extDomain + data.videoPreview + data.uploadId
      }
      document.body.appendChild(oInput)
      oInput.select() // 选择对象
      document.execCommand('Copy') // 执行浏览器复制命令
      oInput.className = 'oInput'
      oInput.style.display = 'none'
      self.$message({
        message: '复制成功!',
        type: 'success'
      })
    },
    commodItem(data) {
      const self = this
      self.customData.commodities = true
      self.customData.commodValue.videoId = data.videoId
      self.commodChange()
    },
    commodChange() {
      const self = this
      const params = {
        pageNo: self.pageData.pageNo,
        pageSize: self.pageData.pageSize
      }
      _api.pageItem(self, params, self.callBack_pageItem, self.customData.commodValue)
    },
    // 分页
    handleSizeChange(val) {
      const self = this
      self.pageData.pageNo = 1
      self.pageData.pageSize = val
      self.commodChange()
    },
    handleCurrentChange(val) {
      const self = this
      self.pageData.pageNo = val
      self.commodChange()
    },
    report() {
      const self = this
      const params = self.searchData
      const time = _tools.getTime()
      const title = 'video_' + time + '.xlsx'
      reportingVideo(params).then(res => {
        if (!_validate.checkEmpty(res.data)) {
          _validate.downloadNotFileName(res, title)
        }
      }).catch(error => {
      })
    }
  }
}
</script>
<style scoped>
.contion-header {
    display: inline-block;
    box-sizing: border-box;
}
.text-r {
    text-align: right;
}
.dece{
    line-height: 20px;
    margin-top: 20px;
}
.dece p{
    padding: 0;
    margin: 0;
    color: #D9001B;
}
</style>
